import logging
log=logging.getLogger(__name__)
import copy
from blog import model
from blog.model import meta
from pylons.controllers.util import abort, redirect_to
from blog.lib.rules import BaseRulesMiddleware

class AuthMiddleware(BaseRulesMiddleware):

    def __init__(self,app,rules):
        BaseRulesMiddleware.__init__(self,app,rules)
        self.set_call(self.call)

    def call(self,environ,start_response,rule):
        rev=bool( rule.get('reversed') )
        if rev ^ ('user' in environ['beaker.session']) :
            return self.app(environ,start_response)
        else :
            abort(403)

def has_right(right,value,way):
    if way == 'manage' :
        if right.manageright & (1 << value ) :
            return True
        else :
            return False
    else:
        if getattr(right,'%sright' % way) >= value :
            return True
        else :
            return False

class CheckRightMiddleware(BaseRulesMiddleware):

    def __init__(self,app,rules):
        BaseRulesMiddleware.__init__(self,app,rules)
        self.set_call(self.call)

    def call(self,environ,start_response,dict_):
        session=environ['beaker.session']
        log.info(session)
        path=environ['PATH_INFO']
        controller=environ['wsgiorg.routing_args'][1].get('controller','')
        action = environ['wsgiorg.routing_args'][1].get('action','')
        if 'user' in session :
            user=session['user']
        else :
            abort(403)
        right=session['right']
        right_=dict_['right']
        way=dict_['way']
        special_user_id=dict_.get('special_user_id',[])
        model_name=dict_.get('model_name',None)
        if model_name :
            model_object_users=dict_.get('model_name_users','users')
            model_object=getattr(model,model_name)
            users=getattr(model_object,model_object_users)
            special_user_id.extend(users)
        routing_args=dict_.get('routing_args')
        if routing_args:
            for args in routing_args:
                uid=int(environ['wsgiorg.routing_args'][1].get(args,None))
                if uid : special_user_id.append(uid)
        if user.id in special_user_id :
            return self.app(environ,start_response)
        elif not has_right(right,right_,way):
            abort(403)
        else :
            return self.app(environ,start_response)
